package yang.yu.sunny.domain;

import org.dayatang.domain.AbstractEntity;

import javax.persistence.*;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 订单
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "order2")
public class Order2 extends AbstractEntity {

    @ManyToOne
    private Customer customer;

    private Long customerId;

    private String customerName;

    @Temporal(TemporalType.TIMESTAMP)
    private Date created;

    private double totalPrice;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private Set<OrderItem2> items = new HashSet<>();

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
        this.setCustomerId(customer.getId());
        this.setCustomerName(customer.getName());
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Set<OrderItem2> getItems() {
        return Collections.unmodifiableSet(items);
    }

    public void setItems(Set<OrderItem2> items) {
        if (items == null) {
            totalPrice = 0;
            this.items = new HashSet<>();
            return;
        }
        this.items = Collections.unmodifiableSet(items);
        totalPrice = this.items.stream().mapToDouble(OrderItem2::getTotalPrice).sum();
    }
}
